package gui.typeEditors;

import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

import javax.swing.JTextField;

import owg.util.Calc;


public class StringEditor extends TypeEditor<String> implements ActionListener, FocusListener
	{
	static final long serialVersionUID = 2704835030524222876L;
	
	final JTextField field;
	String value;
	boolean ignoreEvents = false;
	Color origcolor;
	String filter;
	
	public StringEditor(String initialValue, String filter)
		{
		super();
		this.filter = filter;
		
		field = new JTextField();
		origcolor = field.getBackground();
		field.setColumns(8);
		setValue(initialValue, false);
		add(field);
		field.addActionListener(this);
		field.addFocusListener(this);
		}
	
	@Override
	public void setFont(Font font)
	{
		super.setFont(font);
		if(field != null)//Gets called by super constructor... Otherwise field is always defined.
			field.setFont(font);
	}

	private void setValue(String val, boolean fire)
		{
		String pVal = value;
		val = cleanse(val);
		value = val;
		ignoreEvents = true;
		int ppos = field.getCaretPosition();
		field.setText(val);
		field.setCaretPosition((int)Calc.limit(ppos, 0, field.getText().length()));
		ignoreEvents = false;
		if(fire && ((pVal==null && value!=null) || !pVal.equals(value)))
			{
			fireActionEvents();
			flash(Color.GREEN);
			}
		}
	
	private String cleanse(String val)
		{
		if(filter == null)
			return val;
		return val.replaceAll(filter, "");
		}

	@Override
	public void focusGained(FocusEvent e)
		{}

	@Override
	public void focusLost(FocusEvent e)
		{
		if(!ignoreEvents)
			parseValue();
		}

	@Override
	public void actionPerformed(ActionEvent e)
		{
		if(!ignoreEvents)
			parseValue();
		}

	private void parseValue()
		{
		setValue(field.getText(), true);
		}

	synchronized void color(Color color)
		{
		field.setBackground(color);
		}

	private void flash(Color color)
		{
		color(color);
		flashThread(new Runnable(){public void run(){color(origcolor);}}, 33);
		}

	@Override
	public String getValue()
		{
		return value;
		}
	
	@Override
	public void setValue(String val)
		{
		setValue(val, false);
		}
	@Override
	public void setToolTipTextToSubComponents(String text)
		{
		field.setToolTipText(text);
		}
	@Override
	public void setSubComponentsEnabled(boolean en)
		{
		field.setEnabled(en);
		}
	}
